<template>
<div class="dept-tree">
  <tree
    class = "config-margin"
    @addChild = "addChild"
    @editChild = "editChild"
    @deleteChild = "deleteChild"
    @nodeClick = "nodeClick"
    @moveDept = "moveDept"
    :open = "true"
    :dealTree = "dealTree"
    :treeData = "treeData">
  </tree>
  <add-dept
    :isAdd="isAdd"
    :addForm="addForm"
    @close="cancel"
  >
  </add-dept>
  <edit-dept
    :isEdit="isEdit"
    @close="cancel"
    :editForm="editForm"
  >
  </edit-dept>
</div>
</template>
<script>
  import Tree from './Base/Tree'
  import AddDept from './Base/AddDept'
  import DeleteDept from './Base/DeleteDept'
  import EditDept from './Base/EditDept'
  import { deepClone, isHasMenu } from '@/utils/m7Utils'
  import * as uuid from 'uuid'
  const initForm = {
    _id: '',
    pId: '',
    prentsName: '',
    name: '',
    order: 0,
    observer: [],
    treePath: '',
    note: ''
  }
  export default {
    name: 'DeptTree',
    data () {
      return {
        data: {
          page: 1,
          limit: 10
        },
        dealTree: {},
        depts: [],
        addForm: deepClone(initForm),
        editForm: deepClone(initForm),
        treeData: {},
        isAdd: false,
        isEdit: false
      }
    },
    components: {
      Tree,
      AddDept,
      DeleteDept,
      EditDept
    },
    methods: {
      dealTreeOp () {
        let option = [
          {
            id: 'func_dept_add',
            name: 'add'
          }, {
            id: 'func_dept_delete',
            name: 'delete'
          }, {
            id: 'func_dept_update',
            name: 'edit'
          }, {
            id: 'func_dept_move',
            name: 'move'
          }
        ]
        option.map(item => {
          if (!isHasMenu(item.id, this.$store.state.session.user)) {
            this.dealTree[item.name] = false
            return
          }
          this.dealTree[item.name] = true
        })
      },
      moveDept (data) {
        this.$store.dispatch('moveDept', data).then((res) => {
          if (res && res.success) {
            this.restDeptTree()
          }
        })
      },
      nodeClick (val) {
        this.$emit('nodeClick', val)
      },

      addChild (val) {
        this.isAdd = true
        let temp = deepClone(val)
        delete temp.children
        this.addForm.pId = temp._id
        this.addForm._id = uuid.v1()
        this.addForm.treePath = `${temp.treePath}${this.addForm._id}/`
        this.addForm.prentsName = temp.name
      },

      editChild (val) {
        this.isEdit = true
        let temp = deepClone(val)
        delete temp.children
        this.editForm.pId = temp.pId
        this.editForm._id = temp._id
        this.editForm.treePath = temp.treePath
        this.editForm.prentsName = this.getDeptName(temp.pId)
        this.editForm.observer = temp.observer
        this.editForm.name = temp.name
        this.editForm.note = temp.note
        this.editForm.order = temp.order
      },

      deleteChild (val) {
        if (val.children && val.children.length > 0) {
          this.$message({
            type: 'warning',
            message: this.$t('config.agent.deleteFalse')
          })
          return
        }

        this.$confirm(this.$t('config.agent.confirmDel', {name: val.name}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          type: 'warning',
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn'
        })
        .then(() => {
          this.$store.dispatch('delDept', {deptId: val._id})
          .then(resp => {
            this.restDeptTree().then(() => {
              this.$emit('searchAgent')
            })
            if (resp && resp.success) {
              // this.$store.dispatch('removeCache', { type: 'depts', id: val._id })
              this.$message({
                type: 'success',
                message: this.$t('config.agent.successDel')
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('config.agent.cancelDel')
          })
        })
      },

      getDeptName (id) {
        return this.depts.filter(item => item._id === id)[0].name || ''
      },

      restDeptTree () {
        return this.$store.dispatch('queryDeptList', this.data)
        .then((depts) => {
          let arr = []
          this.depts = depts
          dealDept(depts, arr, '')
          this.treeData = deepClone(arr[0])
        })
      },

      cancel (data) {
        if (data.type === 'submit') {
          this.isEdit = data.bool
          this.isAdd = data.bool
          this.restDeptTree().then(() => {
            this.$emit('searchAgent')
          })
        } else {
          this.isEdit = data.bool
          this.isAdd = data.bool
        }
      }
    },
    beforeMount () {
      this.restDeptTree()
      this.dealTreeOp()
    }
  }
  function dealDept (depts, arr, key) {
    for (let i in depts) {
      let dept = depts[i]
      if (dept.pId === key) {
        let obj = {
          _id: dept._id,
          type: 'dept',
          treePath: dept.treePath,
          observer: dept.observer,
          note: dept.note,
          pId: dept.pId,
          name: dept.name,
          order: dept.order || 0,
          children: []
        }
        arr.push(obj)
        dealDept(depts, obj.children, dept._id)
      }
    }
  }
</script>
<style lang="stylus" scoped>
  .dept-tree
    overflow-y auto
    height calc(100vh - 140px)
  .config-margin
    margin-top 20px
</style>
